﻿using web_api_demo101.Entities;
using web_api_demo101.Repositories.Impl;

namespace web_api_demo101.Services.Impl;

public class UserService
{
    private readonly UserRepository _userRepository;

    public UserService()
    {
        _userRepository = new UserRepository();
    }
    public bool Reg(User user)
    {
        if (string.IsNullOrWhiteSpace(user.Email) || string.IsNullOrWhiteSpace(user.Password))
        { 
            //throw exception
            return false;
        }
        user.RegTime = DateTime.Now;
        user.Status = true; // 正常情况是`false` , 邮件激活了之后再设置为`true`

        var count = _userRepository.Add(user);

        return count > 0;
    }

    public bool Login(User user)
    {
        if (string.IsNullOrWhiteSpace(user.Email) || string.IsNullOrWhiteSpace(user.Password))
        {
            //throw exception
            return false;
        }

        var target = _userRepository.GetByEmail(user.Email);
        if (target == null) { 
            return false;
        }

        if (!target.Password.Equals(user.Password)) { 
            return false;
        }

        target.LastLoginTime = DateTime.Now;
        _userRepository.Update(user);

        return true;
    }

    public User? GetById(int id)
    { 
        return _userRepository.GetById(id);
    }

    public User? GetByEmail(string email)
    { 
        return _userRepository.GetByEmail(email);
    }

    public bool ExistsByEmail(string email)
    { 
        return _userRepository.GetByEmail(email) != null;
    }

    public List<User> List() { 
        return _userRepository.List();
    }
}
